package com.bs.service;

import com.bs.domain.Deploy;
import com.bs.domain.DeployArchive;
import com.bs.repository.DeployArchiveRepository;
import com.bs.repository.DeployRepository;
import com.bs.service.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.sql.Timestamp;
import java.util.*;

/**
 * Created by wenguangjia on 2017/4/25.
 */
@Service
@Transactional
public class DeployService {
    private static final Logger log = LoggerFactory
        .getLogger(DeployService.class);

    @Autowired
    private DeployRepository deployRepository;

    @Autowired
    private DeployArchiveRepository deployArchiveRepository;

    /**
     * 获取分区列表
     * @return
     */
    public List<Deploy> getPartitions() {

        List listAll = new ArrayList();
        List list1 = deployRepository.getPartitions();
        List list2 = deployArchiveRepository.getPartitions();
        listAll.addAll(list1);
        listAll.addAll(list2);
        listAll = new ArrayList(new LinkedHashSet<>(listAll));
        Collections.sort(listAll);
        return listAll;
    }

    public List<Deploy> query(Deploy deploy) {
        log.info(deploy.toString());

        List list = null;

        if(deploy.getArchive()){
            DeployArchive deployArchive=new DeployArchive();
            deployArchive.setState(deploy.getState());
            deployArchive.setTitle(deploy.getTitle());
            deployArchive.setSubmitDate(deploy.getSubmitDate());
            deployArchive.setSubmitDateEnd(deploy.getSubmitDateEnd());
            deployArchive.setPart(deploy.getPart());
            list = deployArchiveRepository.findAll(where2(deployArchive));

        }else{
            list = deployRepository.findAll(where(deploy));
        }
        return list;
    }



    public Deploy create(Deploy deploy) throws Exception {

        log.info("create start:" + deploy.toString());

        if (deploy.getTitle() == null || deploy.getTitle().equals("")) {
            throw new Exception("标题不能为空!");
        }
        deploy.setSubmitDate(DateUtil.getTime());

        if (deploy.getState() == null) {
            deploy.setState(0);
        }

        Deploy deploy1 = deployRepository.save(deploy);

        log.info("create end:" + deploy1.toString());
        return deploy;
    }


    public void update(Deploy deploy) throws Exception {

        log.info("update start===" + deploy);

        Deploy result = deployRepository.findOne(deploy.getId());
        if (result == null) {
            throw new Exception("no this id,please check again");
        }else{
            if (deploy.getState() != null) {
                result.setState(deploy.getState());
            } else {
                result.setState(1);
            }
            result.setFinishDate(DateUtil.getTime());
            deployRepository.save(result);
        }

    }


    /**
     * 条件查询时动态组装条件
     */
    private Specification<Deploy> where(Deploy deploy) {
        return new Specification<Deploy>() {
            @Override
            public Predicate toPredicate(Root<Deploy> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                //ID
//                if (deploy.getId() != null && deploy.getId() != 0) {
//                    predicates.add(cb.equal(root.<String>get("id"), deploy.getId()));
//
//                }
                //审批状态
                if (deploy.getState() != null && !deploy.getState().equals("")) {
                    predicates.add(cb.equal(root.<String>get("state"), deploy.getState()));
                }
                //标题
                if (deploy.getTitle() != null && !deploy.getTitle().equals("")) {
                    predicates.add(cb.like(root.<String>get("title"), "%"+deploy.getTitle()+"%"));
                }

                //类型
                if (deploy.getType() != null && !deploy.getType().equals("")) {
                    predicates.add(cb.equal(root.<String>get("type"), deploy.getType()));
                }

                //模块
                if (deploy.getModule() != null && !deploy.getModule().equals("")) {
                    predicates.add(cb.like(root.<String>get("module"), "%"+deploy.getModule()+"%"));
                }

                //分区
                if (deploy.getPart() != null && !deploy.getPart().equals("")) {
                    predicates.add(cb.equal(root.<String>get("part"), deploy.getPart()));
                }

                //日期
                if (deploy.getSubmitDate() != null) {
                    predicates.add(cb.between(root.<Timestamp>get("submitDate"), deploy.getSubmitDate(), deploy.getSubmitDateEnd()));
                }
                return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
            }
        };
    }

    /**
     * 查询归档记录
     * 条件查询时动态组装条件
     */
    private Specification<DeployArchive> where2(DeployArchive deploy) {
        return new Specification<DeployArchive>() {
            @Override
            public Predicate toPredicate(Root<DeployArchive> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                //ID
//                if (deploy.getId() != null && deploy.getId() != 0) {
//                    predicates.add(cb.equal(root.<String>get("id"), deploy.getId()));
//
//                }
                //审批状态
                if (deploy.getState() != null && !deploy.getState().equals("")) {
                    predicates.add(cb.equal(root.<String>get("state"), deploy.getState()));
                }
                //标题
                if (deploy.getTitle() != null && !deploy.getTitle().equals("")) {
                    predicates.add(cb.like(root.<String>get("title"), "%"+deploy.getTitle()+"%"));
                }

                //类型
                if (deploy.getType() != null && !deploy.getType().equals("")) {
                    predicates.add(cb.equal(root.<String>get("type"), deploy.getType()));
                }

                //模块
                if (deploy.getModule() != null && !deploy.getModule().equals("")) {
                    predicates.add(cb.like(root.<String>get("module"), "%"+deploy.getModule()+"%"));
                }

                //分区
                if (deploy.getPart() != null && !deploy.getPart().equals("")) {
                    predicates.add(cb.equal(root.<String>get("part"), deploy.getPart()));
                }

                //日期
                if (deploy.getSubmitDate() != null) {
                    predicates.add(cb.between(root.<Timestamp>get("submitDate"), deploy.getSubmitDate(), deploy.getSubmitDateEnd()));
                }
                return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
            }
        };
    }
}
